#!/usr/bin/env python
# coding: utf-8
# author: Wesley

import logging

from django.conf import settings
from django.http import JsonResponse

from lib.common import AbstractHandler
from lib.sms import sender
from services.datamodel.student.models import mm_Student

app_logger = logging.getLogger("parent")


class CodeHandler(AbstractHandler):
    def __init__(self):
        AbstractHandler.__init__(self, app_logger)

    # @ratelimit(key='post:target',rate='1/m')
    # @ratelimit(key='get:target',rate='1/m')
    def handle_send(self, request):
        """
        Request sample:
            curl --cookie "sessionid=sovsxvzb76ycum7tyxqcodlky1pslg35"
            "http://127.0.0.1:8000/api/sms/sendcode/?target=18652701182&sign=b29f8a1b355228b0391ef0915f8f06a4&stype=MREGISTER"
            
        """
        for param in ['target', 'sign', 'stype']:
            if param not in request.REQUEST:
                return JsonResponse({
                    'retcode': 1,
                    'msg': "缺少参数`%s`" % param
                })
        if getattr(request, 'limited', False):
            return JsonResponse({'retcode': settings.RATELIMITTED_CODE, 'msg': '获取验证码失败,请稍后再试'})
         
        target = request.REQUEST.get('target')
        sign = request.REQUEST.get('sign')
        stype = request.REQUEST.get('stype')
        mcc = request.REQUEST.get('mcc', '86')
        #  if stype != 'MLOGIN' and hasattr(request.user, 'student'):
        if stype in ['WREGISTER', 'MREGISTER', 'WCHANGEPHONE', 'MCHANGEPHONE', 'FORGETPASSWORD',
                     'WECHATCONNECT'] and hasattr(request.user, 'student'):
            try:
                mm_Student.is_unique_phonenumber_in_students(target, is_raise=True)
            except AssertionError as e:
                ret = {"retcode": e.args[0][0], "msg": e.args[0][1]}
                return JsonResponse(ret)
        ret = sender.sendcode(stype, target, sign, mcc=mcc)
        return JsonResponse(ret)
    
    def handle_check(self, request):
        """
        Request sample:
            curl "http://127.0.0.1:8000/api/sms/checkcode/?target=18652701182&code=1640"
            
        """
        for param in ['target', 'code', 'stype']:
            if param not in request.REQUEST:
                return JsonResponse({
                    'retcode': 1,
                    'msg': "缺少参数`%s`" % param
                })
        #
        #         tasktype = request.param_dict['tasktype']
        #         rid = request.param_dict['rid']
        target = request.REQUEST.get('target')
        codenumber = request.REQUEST.get('code')
        stype = request.REQUEST.get('stype')
        ret = sender.checkcode(stype, target, codenumber)
        return JsonResponse(ret)


handler = CodeHandler()
